package com.lovezy.platform.interceptor;

import com.lovezy.platform.core.base.SiteContext;
import com.lovezy.platform.core.exception.RequestErrorException;
import com.lovezy.platform.core.jwt.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.lovezy.platform.core.exception.DefaultErrorCode.NOT_LOGIN;

/**
 * 前端拦截器
 * Created by jin on 2017/11/14.
 */
public class FrontInterceptor extends TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String authorization = httpServletRequest.getHeader("Authorization");
        if (authorization == null) {
            throw new RequestErrorException(NOT_LOGIN, "未登录");
        }
        Map<String, Object> claims = JwtUtil.parserJavaWebToken(authorization);
        if (claims == null) {
            throw new RequestErrorException(NOT_LOGIN, "未登录");
        }
        String mid = doCheckValid(claims);
        SiteContext.setCurrentMid(mid);
        return true;
    }

    private String doCheckValid(Map<String, Object> claims) {
        TokenValidResult tokenValidResult = checkValid(claims);
        if (!tokenValidResult.isSuccess()) {
            throw new RequestErrorException(tokenValidResult.getErrorCode(), tokenValidResult.getErrorMsg());
        }else{
            return tokenValidResult.getMid();
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        SiteContext.clearCurrentMid();
    }
}
